package com.psm.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.psm.enums.MenuType;
import com.psm.interceptor.IndexInterceptor;
import com.psm.model.DataGrid;
import com.psm.model.SysPaCode;
import com.psm.model.WXMenu;
import com.psm.model.WxSetting;
import com.psm.weixin.AccessToken;
import com.psm.weixin.AccessTokenApi;
import com.psm.weixin.ApiConfig;
import com.psm.weixin.ApiConfigKit;
import com.psm.weixin.Menu;
import com.psm.weixin.MenuButton;
import com.psm.weixin.ReturnCode;
import com.psm.weixin.api.ApiResult;
import com.psm.weixin.api.MenuApi;

/**
 * 
 * @author 广州朴石茗文化发展有限公司 @Email pushiming@sina.cn
 * Jul 23, 2015 
 * TODO
 */
@Before(IndexInterceptor.class)
public class WXMenuController extends BaseController<WXMenu>{
	
	public Logger log=Logger.getLogger(getClass());
	public static String appid = null;
	/**
	 * 主页
	 */
    public void index(){
    	loadAccessToken();
        render("index.html");
    }
    /**
	 * 系统启动，重新获取所有公众号accesstoken
	 */
	public void loadAccessToken(){
		System.out.println("===================================loadAccessToken");
		List<WxSetting> wxsetting = WxSetting.wx.find("select t.* from "+WxSetting.tableName + " t where 1=1");
		if(wxsetting.size()>0){
				System.out.println(wxsetting.get(0).getStr("appid")+"============================="+wxsetting.get(0).getStr("secret"));
	        	 ApiConfig ac = new ApiConfig();
	     		 ac.setAppId(wxsetting.get(0).getStr("appid"));
	     		 ac.setAppSecret(wxsetting.get(0).getStr("secret"));
	     		 this.appid = wxsetting.get(0).getStr("appid");
	     		 ApiConfigKit.setThreadLocalApiConfig(ac);
	     		 
	     		 AccessToken at = AccessTokenApi.getAccessToken();

//	     		 ApiConfigKit.removeThreadLocalApiConfig();
		}
	}
    /**
     * 列表数据
     */
    public void listJson(){

        List<Object> param = new ArrayList<Object>();
 
        Page<Record> p = Db.paginate(this.getParaToInt("page", 1), this.getParaToInt("rows", 20), "select t.*,a.name as tname,b.name as sname,c.menu_name as pname ", "from " + WXMenu.tableName + " t left join sys_pa_code a on t.menu_type = a.id left join sys_pa_code b on t.status = b.id left join wx_menu c on t.parent_id = c.id where 1=1 ", param.toArray());
        DataGrid dg = new DataGrid();
        dg.setRows(p.getList());
        dg.setTotal(p.getTotalRow());

        renderJson(dg);

    }
    /**
     * 编辑、添加页
     */
    public void edit() {
        try {
        	log.debug("wxsetting-edit=================================");
            Long id = getParaToLong("id");
            
            WXMenu wx = WXMenu.wx.findById(id);;
            this.setAttr("po",wx);
        } catch (Exception e) {
            log.error("编辑异常", e);
        }
    }
    
    /**
     * 保存信息
     */
    public void save(){
    	/**
    	 * 获取数据
    	 */
    	 String id = getPara("id","");
         String pid = getPara("parent_id","");
         String type = getPara("menu_type","");
         String name = getPara("menu_name","");
         String key = getPara("menu_key","");
         String url = getPara("menu_url","");
         String status = getPara("status","0");
         /**
          * 新建对象
          */
         WXMenu wx = null;
         if("".equals(id)){
             wx = new WXMenu();
         }else{
             wx = WXMenu.wx.findById(id);
         }
         if("".equals(pid)){
        	 wx.set("parent_id", 0);
         }else{
        	 wx.set("parent_id", pid);
         }
         
         
         wx.set("menu_type", type);
         wx.set("menu_name", name);
         wx.set("menu_key", key);
         wx.set("menu_url", url);
         wx.set("status", status);
         /**
          * 更新数据
          */
         if("".equals(id)){
             wx.save();
         }else{
             wx.update();
         }
         this.rendJson_(1, "操作成功");
    }
    /**
     * 
     * @param config
     */
    public void createMenu() {
    	
    	System.out.println("===================================createMenu");
    	
    	loadAccessToken();
        
        Menu request = new Menu();
        
        List<WXMenu> wxsetting = WXMenu.wx.find("select t.* from "+WXMenu.tableName + " t where 1=1  and parent_id = 0");
        if(wxsetting != null&&wxsetting.size()>0){
	        for (int i = 0; i < wxsetting.size(); i++) {
	        	//一级菜单
	        	MenuButton main1 = new MenuButton();
	            main1.setType(MenuType.CLICK);
	            main1.setKey(wxsetting.get(i).getStr("menu_key"));
	            main1.setName(wxsetting.get(i).getStr("menu_name"));
	            //二级菜单
	            List<WXMenu> menuList = WXMenu.wx.find("select t.*,a.name as tname from "+WXMenu.tableName+" t left join sys_pa_code a on t.menu_type = a.id where 1=1  and parent_id = "+wxsetting.get(i).getLong("id"));
	            if(menuList != null&&menuList.size()>0){
	            	List<MenuButton> list = new ArrayList<MenuButton>();
	            	List<MenuButton> mList = new ArrayList<MenuButton>();
	            	for (int j = 0; j < menuList.size(); j++) {
	            		MenuButton sub1 = new MenuButton();
	                    sub1.setKey(menuList.get(j).getStr("menu_key"));
	                    sub1.setName(menuList.get(j).getStr("menu_name"));
	                    if("view".equals(menuList.get(j).getStr("tname"))){
	                    	sub1.setType(MenuType.VIEW);
		                    sub1.setUrl(menuList.get(j).getStr("menu_url"));
	                    }else if("click".equals(menuList.get(j).getStr("tname"))){
	                    	sub1.setType(MenuType.CLICK);
	                    }
	                    list.add(sub1);
					}
	            	main1.setSubButton(list);
	            	mList.add(main1);
	            	//将主菜单加入请求对象
	                request.setButton(mList);
	                //创建菜单
	                System.out.println(request.toJsonString()+"======menuJson");
	                
	                ApiResult apiResult = MenuApi.createMenu(request.toJsonString());
	                
	                System.out.println("apiresult============"+apiResult.getErrorCode()+"=========="+ReturnCode.get(apiResult.getErrorCode()));
	                this.rendJson_(1, "操作成功");
	            }else{
	            	this.rendJson_(1, "无效数据");
	            }
			}
        }else{
        	this.rendJson_(1, "无效数据");
        }
        /**
        //准备一级主菜单
        MenuButton main1 = new MenuButton();
        main1.setType(MenuType.CLICK);
        main1.setKey("main1");
        main1.setName("测试");
        //准备子菜单
        MenuButton sub1 = new MenuButton();
        sub1.setKey("sub1");
        sub1.setName("授权");
        sub1.setType(MenuType.VIEW);
        sub1.setUrl("http://baidu.com");
        MenuButton sub2 = new MenuButton();
        sub2.setKey("sub2");
        sub2.setName("点击");
        sub2.setType(MenuType.CLICK);


        List<MenuButton> list = new ArrayList<MenuButton>();
        list.add(sub1);
        list.add(sub2);
        //将子菜单放入主菜单里
        main1.setSubButton(list);

        List<MenuButton> mainList = new ArrayList<MenuButton>();
        mainList.add(main1);
        
        
        //将主菜单加入请求对象
        request.setButton(mainList);
        //创建菜单
        ApiResult apiResult = MenuApi.createMenu(request.toJsonString());
        
        this.rendJson_(1, apiResult.toString());
        **/
        //this.rendJson_(1, wxsetting.size()+"");
        //this.rendJson_(1, "操作成功");
        
    }
    
    /**
     * 一级菜单列表
     */
    public void get_p_menu(){

        List<Record> list= Db.find("select * from " + WXMenu.tableName+" where parent_id = 0",new Object[]{});
        this.renderJson(list);
    }

}
